<?php

namespace App\Repository\Order;

use App\Jobs\Subpackage;
use App\Libs\PhpOffice\Excel;
use App\Models\Order\OrderExportModel as model;
use App\Repository\Anchor\AnchorStatsRepository;
use App\Repository\BaseRepository;
use App\Repository\CatchConf\DouYinCatchRepository;
use App\Repository\CatchConf\PddCatchRepository;
use App\Repository\Information\InformationOrdersRepository;
use App\Repository\Orders\OrdersRepository;
use App\Repository\Product\GoodsRepository;
use App\Repository\Stock\StockOrderRepository;

class OrderExportRepository extends BaseRepository
{
    private $model;
    private $modelInfo;
    private $logModel;
    private $productModel;
    private $goodsModel;

    public function __construct()
    {
        $this->model = new model();
        $this->modelInfo = new OrderInfoRepository();
        $this->logModel = new OrderLogRepository;
        $this->productModel = new OrderProductRepository;
        $this->goodsModel = new GoodsRepository();
        parent::__construct();
    }

    //列表
    public function index($where)
    {
        $cron = $where;
        $cron['order'] = ['orderby' => 'id', 'orderdir' => 'desc'];
        // $cron['where'] = $where;
        // var_dump($cron,111111111);
        // var_dump($cron, 444444444);
        $data = $this->search($this->model, $cron);
        return $data;
    }

    //添加
    public function add($data)
    {
        //必填 字段
        $mustField = [
            'name',
        ];
        $optionalFields = $this->model->getTableField();
        $msgField = [
            'name' => '导出单名称不能为空',
        ];

        $insertData = $this->getRealData($data, $mustField, $optionalFields, $msgField);
        if (!empty($insertData) && is_string($insertData)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $insertData
            );
        }
        if (!empty($insertData['type'])) {
            $insertData['type_name'] = $this->model->getOrderSource($insertData['type']);
        }
        $insertData['shop_id'] = $data->user->shop_id;
        $insertData['created_by'] = $data->user->id;
        $insertData['created_by_name'] = $data->user->nick_name;
        $insertData['created_at'] = date('Y-m-d H:i:s');
        $res = $this->model->insertGetId($insertData);
        if ($res) {
////            直接执行,不用队列
//            $model = new LongFileRepository();
//            $model->readDataAll($res, 'readPushOrderData');
//            这里是用队列方式
            dispatch(new Subpackage($res, 'readPushOrderData'))->onQueue('TaskLongFileDispose');
            return $this->returnMsg(200, '设置成功,稍后请在导出列表里下载');
        }
        return $this->returnMsg(1, '上传失败');
    }

    //删除
    public function del($where)
    {
        $flag = true;
        $msg = '未知错误';
        $code = 1;
        if (empty($where)) {
            $flag = false;
            $msg = '删除条件不能为空';
            $code = 2;
        }
        if ($flag) {
            $res = $this->model->where($where)->get();
            if (!$res) {
                $flag = false;
                $msg = '未查询到数据';
                $code = 3;
            }
        }
        if ($flag) {
            $del = $this->model->where($where)->delete();
            if ($del) {
                $msg = '删除成功';
                $code = 200;
            }
        }
        return $this->returnMsg($code, $msg);
    }

    public function getOne($where, $field = ['*'])
    {
        return $this->model->where($where)->select($field)->first();
    }

    //数据导出 这个是老版本
    public function excelPort_back($id)
    {
        // 查询出来数据
        $getOneData = $this->getOne(['id' => $id]);
        // var_dump($getOneData, 4444444);
        if (!$getOneData) {
            return $this->returnMsg(1, '未查询到文件');
        }
        if ($getOneData->type == 1) {
            // 抖音订单导出
            $model = new DouYinCatchRepository();
            return $model->getExcelPort($id, $getOneData->parame, $getOneData->name, $getOneData->shop_id);
        }
        if ($getOneData->type == 3) {
            // 财务订单的导出
            return $this->excelPortfinance($id, $getOneData->parame, $getOneData->name, $getOneData->shop_id);
        }
        $where = [];
        // $where['where']['shop_id'] = $getOneData->shop_id;
        $model = new OrdersRepository();
        if (!empty($getOneData->parame)) {
            $request = json_decode($getOneData->parame, true);
            if (empty($request['is_dist'])) {
                $where['where']['shop_id'] = $getOneData->shop_id;
            }
            if (!empty($request['is_dist'])) {
                $where['like']['shop_id_str'] = '.' . $getOneData->shop_id . '.';
            }
            if (isset($request['is_sign']) && $request['is_sign'] != '') {
                $where['where']['is_sign'] = $request['is_sign'];
            }
            if (!empty($request['status'])) {
                $where['where']['status'] = $request['status'];
            }
            if (!empty($request['orderno'])) {
                $where['where']['orderno'] = trim($request['orderno'], ' ');
            }
            if (!empty($request['source'])) {
                $where['where']['source'] = trim($request['source'], ' ');
            }
            if (!empty($request['three_msg'])) {
                $where['like']['three_msg'] = $request['three_msg'];
            }
            if (!empty($request['sell_name'])) {
                $where['where']['sell_name'] = $request['sell_name'];
            }
            if (!empty($request['goods_id']) && empty($request['is_dist'])) {
                $where['where']['goods_id'] = $request['goods_id'];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            if (!empty($request['goods_id']) && !empty($request['is_dist'])) {
                $where['like']['sup_goods_id_str'] = '.' . $request['goods_id'] . '.';
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            if (!empty($request['pay_identity'])) {
                $where['where']['pay_identity'] = trim($request['pay_identity'], ' ');
            }
            if (!empty($request['sup_orderno'])) {
                $where['where']['sup_orderno'] = $request['sup_orderno'];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            if (!empty($request['dist_orderno'])) {
                $where['where']['dist_orderno'] = $request['dist_orderno'];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            if (!empty($request['iccid'])) {
                $where['where']['iccid'] = $request['iccid'];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            if (!empty($request['express_number'])) {
                $where['where']['express_number'] = $request['express_number'];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            if (!empty($request['contact_phone'])) {
                $where['where']['contact_phone'] = $request['contact_phone'];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            if (!empty($request['contact_name'])) {
                $where['where']['contact_name'] = $request['contact_name'];
            }
            if (!empty($request['number'])) {
                $where['like']['name'] = $request['number'];
            }
            if (!empty($request['province'])) {
                $where['like']['post_province'] = $request['province'];
            }
            if (!empty($request['city'])) {
                $where['like']['post_city'] = $request['city'];
            }
            if (!empty($request['author_id'])) {
                $where['where']['author_id'] = $request['author_id'];
            }
            //时间验证
            if (!empty($request['dateRange'])) {
                // $time = $request->get('dateRange');
                $where['between'] = ['created_at' => $request['dateRange']];
            }
        }
        $where['limit']['start'] = 0;
        $where['limit']['number'] = 50000;
        // var_dump($where);
        $resData = $model->index($where);
        // var_dump($resData);
        $model = new Excel();
        $title = [
            '订单编号',
            '上游编号',
            '下游编号',
            '来源',
            '分销商',
            '商品名称',
            '用户姓名',
            '用户联系电话',
            '证件信息',
            '购买手机号',
            '购买手机号的串号',
            '省',
            '市',
            '区',
            '详细地址',
            '订单状态',
            '提交失败信息',
            '当前渠道',
            '失败信息',
            '达人id',
            '达人昵称',
            '快递名称',
            '快递单号',
            '分销商',
            '上游返回状态',
            '提交时间',
        ];
        $excelData = [];
        foreach ($resData['data'] as $key => $v) {
            // 处理失败的信息
            $str = '';
            if (!empty($v['channel_error_josn']) && $v['channel_error_josn'] != '[]' && is_string($v['channel_error_josn'])) {
                $arrayError = json_decode($v['channel_error_josn'], true);
                foreach ($arrayError as $keys => $val) {
                    $str .= '渠道:' . $val['channel_name'] . '失败信息' . $val['msg'];
                }
            }
            $excelData[] = [
                $v['orderno'],
                $v['sup_orderno'],
                $v['dist_orderno'],
                $v['source_type'],
                $v['shop_name'],
                $v['goods_name'],
                $v['pay_name'],
                $v['pay_phone'],
                $v['pay_identity'] . ' ',
                $v['iccid'],
                $v['imei'],
                $v['post_province'],
                $v['post_city'],
                $v['post_area'],
                $v['post_address'],
                $v['status_desc'],
                $str,
                $v['sup_name'],
                !empty($v['three_msg']) ? $v['three_msg'] : '',
                $v['author_id'],
                $v['author_name'],
                $v['express_company'],
                $v['express_number'],
                $v['sell_name'],
                $v['card_status_desc'],
                $v['created_at']
            ];
        }
        $fielname = '/attach/excel/' . $getOneData->name . date('YmdHis') . '.xlsx';
        $model->exportFile($excelData, $title, $fielname);
        $this->model->where(['id' => $id])->update(['is_run' => 1, 'path' => $fielname]);
        return $this->returnMsg(200, '导出成功', ['fiel' => $fielname]);
    }

    public function excelPort($id)
    {
        // 查询出来数据
        $getOneData = $this->getOne(['id' => $id]);
        // var_dump($getOneData, 4444444);
        if (!$getOneData) {
            return $this->returnMsg(1, '未查询到文件');
        }
        if ($getOneData->type == 1) {
            // 抖音订单导出
            $model = new DouYinCatchRepository();
            return $model->getExcelPort($id, $getOneData->parame, $getOneData->name, $getOneData->shop_id);
        }
        if ($getOneData->type == 3) {
            // 财务订单的导出
            return $this->excelPortfinance($id, $getOneData->parame, $getOneData->name, $getOneData->shop_id);
        }
        if ($getOneData->type == 4) {
            $model = new StockOrderRepository();
            return $model->getExcelPort($id, $getOneData->parame, $getOneData->name, $getOneData->shop_id);
        }
        if ($getOneData->type == 5) {
            $model = new PddCatchRepository();
            return $model->getExcelPort($id, $getOneData->parame, $getOneData->name, $getOneData->shop_id);
        }
        if ($getOneData->type == 6) {
            $model = new InformationOrdersRepository();
            return $model->getExcelPort($id, $getOneData->parame, $getOneData->name, $getOneData->shop_id);
        }
//    导出直播当前数据的操作
        if ($getOneData->type == 7) {
            $Repository = new AnchorStatsRepository();
            return $Repository->getExcelPort($id, $getOneData->parame, $getOneData->name, $getOneData->type);
        }
//        导出直播达人订单数据的下载
        if ($getOneData->type == 8) {
            $Repository = new AnchorStatsRepository();
            return $Repository->downloadExcelPort($id, $getOneData->parame, $getOneData->name, $getOneData->type);
        }
//        导出订单查询内容

        $where = [];
        $shopS = $getOneData->shop_id;
        // $where['where']['shop_id'] = $getOneData->shop_id;
        $model = new OrdersRepository();
        if (!empty($getOneData->parame)) {
            $request = json_decode($getOneData->parame, true);
            $request['user']['shop_id'] = $shopS;
            $where = $model->indexWhere($request);
        }
        //        拉黑的不能导
        $where['where']['orders.blocking'] = 0;
        $where['limit']['start'] = -1;
        $where['limit']['number'] = 50000;
//        print_r($where);
        $resData = $model->index($where, $shopS, true);
        $model = new Excel();
        $title = [
            '订单编号',
            '上游编号',
            '下游编号',
            '来源',
            '分销商',
            '商品名称',
            'SKU靓号',
            '靓号归属地',
            '归属客服',
            '用户姓名',
            '用户联系电话',
            '证件信息',
            '购买手机号',
            '购买手机号的串号',
            '省',
            '市',
            '区',
            '详细地址',
            '订单状态',
            '提交失败信息',
            '当前渠道',
            '上游信息',
            '主播名称',
            '开播时间',
            '下播时间',
            '达人id',
            '达人昵称',
            '快递名称',
            '快递单号',
            '上游返回状态',
            '激活状态',
            '激活时间',
            '首充状态',
            '充值金额',
            '充值时间',
            '在网状态',
            '提交时间',
            '订单备注'
        ];
        $excelData = [];
        $ordersStatusList = config('card.ordersStatus');
        $activatStatusList = config('card.activatStatus');
        $firstStatusList = config('card.firstStatus');
        $isOnlineStatusList = config('card.isOnlineStatus');
//        print_r($resData['data']);
        foreach ($resData['data'] as $key => $v) {
            // 处理失败的信息
            $str = '';
            if (!empty($v['channel_error_josn']) && $v['channel_error_josn'] != '[]' && is_string($v['channel_error_josn'])) {
                $arrayError = json_decode($v['channel_error_josn'], true);
                foreach ($arrayError as $keys => $val) {
                    $str .= '渠道:' . $val['channel_name'] . '失败信息' . $val['msg'];
                }
            }
            // 判断是否是代理订单
            // if (!empty($v->shop_id_str)) {
            //   $shopArr = explode('.', $v->shop_id_str);
            //   if ($shopArr[0] != $shopS) {
            //     $v['sup_name'] = '';
            //     $v['sup_orderno'] = '';
            //   }
            // }
            if (empty(env('IS_ENCRYP')) || env('IS_ENCRYP') != 2) {
                if (!empty($v['pay_identity'])) {
                    $v['pay_identity'] = str_replace(mb_substr($v['pay_identity'], 3, 11), '*******', ($v['pay_identity']));
                }
            }
            if (isset($v['skumark']) && !empty($v['skumark'])) {
                preg_match('/([0-9]{11,13})/', $v['skumark'], $tmp);
                if (!empty($tmp)) {
                    $v['skumark'] = $tmp[1];
                }
                $v['iccid'] = empty($v['iccid']) ? $v['skumark'] : $v['iccid'];
            }
//            订单状态,现在只根据配置
            $v['status_desc'] = $ordersStatusList[$v['status']] ?? $v['status'];
            $v['activat_status_desc'] = $activatStatusList[$v['activat_status']] ?? '';
            $excelData[] = [
                $v['ordersno'],
                $v['sup_orderno'],
                $v['dist_orderno'],
                $v['source_type'],
                $v['shop_name'],
                $v['goods_name'],
                $v['sku_number'] ?? '',
                $v['sku_area'] ?? '',
                $v['service_user_name'] ?? '',
                $v['pay_name'],
                $v['pay_phone'],
                $v['pay_identity'] . ' ',
                $v['iccid'],
                $v['imei'],
                $v['post_province'],
                $v['post_city'],
                $v['post_area'],
                $v['post_address'],
                $v['status_desc'],
                $str,
                $v['sup_name'],
                !empty($v['three_msg']) ? $v['three_msg'] : '',
                $v['anchor_name'] ?? '',
                $v['anchor_created_at'] ?? '',
                $v['anchor_over_at'] ?? '',
                $v['author_id'],
                $v['author_name'],
                $v['express_company'],
                $v['express_number'],
                $v['card_status_desc'],
                $v['activat_status_desc'],
                $v['activat_at'] ?? '',
                $firstStatusList[$v['first_status']] ?? '',
                $v['first_money'] ?? '',
                $v['first_status_at'] ?? '',
                $isOnlineStatusList[$v['is_online']] ?? '',
                $v['created_at'],
                $v['remark']
            ];
        }
        $fielname = '/attach/excel/2/' . date('Ym') . '/' . $getOneData->name . date('YmdHis') . '.xlsx';
        $model->exportFile($excelData, $title, $fielname);
        $this->model->where(['id' => $id])->update(['is_run' => 1, 'path' => $fielname]);
        return $this->returnMsg(200, '导出成功', ['fiel' => $fielname]);
    }

    public function excelPortfinance($id, $getOneData = '', $name = '', $shop_id = 0)
    {

        $where = [];
        // $where['where']['shop_id'] = $getOneData->shop_id;
        $model = new OrdersRepository();
        if (!empty($getOneData)) {
            $request = json_decode(($getOneData), true);
            // if (empty($request['is_dist'])) {
            //   $where['where']['shop_id'] = $shop_id;
            // }
            // if (!empty($request['is_dist'])) {
            //   $where['like']['shop_str'] = $shop_id;
            // }
            if (!empty($request['status'])) {
                $where['where']['orders.status'] = $request['status'];
            }
            if (!empty($request['source'])) {
                $where['where']['orders_user.source'] = $request['source'];
            }
            if (!empty($request['ordersno'])) {
                $where['where']['orders.ordersno'] = trim($request['ordersno'], ' ');
            }
            if (!empty($request['three_msg'])) {
                $where['like']['orders.three_msg'] = $request['three_msg'];
            }
            if (!empty($request['sell_name'])) {
                $where['where']['orders_user.sell_name'] = $request['sell_name'];
            }
            if (!empty($request['goods_id']) && empty($request['shop_id'])) {
                // $where['where']['order.goods_id'] = $request['goods_id'];
                $where['whereors'] = [
                    'where' => ['orders.goods_id' => $request['goods_id']],
                    'whereor' => [['orders.sup_goods_id_str', 'like', '%.' . $request['goods_id'] . '.%']]
                ];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            if (!empty($request['goods_id']) && !empty($request['shop_id'])) {
                $where['like']['orders.sup_goods_id_str'] = '%.' . $request['goods_id'] . '.%';
                // $where['whereor'][] = [
                //   'where' => ['order.goods_id' => $request['goods_id']],
                //   'whereor' => [['order.sup_goods_id_str', 'like', '%.' . $request['goods_id'] . '.%']]
                // ];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }

            if (!empty($request['pay_identity'])) {
                $where['where']['orders_user.pay_identity'] = trim($request['pay_identity'], ' ');
            }
            if (!empty($request['sup_orderno'])) {
                $where['where']['orders_user.sup_orderno'] = $request['sup_orderno'];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            if (!empty($request['dist_orderno'])) {
                $where['where']['orders_user.dist_orderno'] = $request['dist_orderno'];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            if (!empty($request['iccid'])) {
                $where['where']['orders_user.iccid'] = $request['iccid'];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            if (empty($request['shop_id'])) {
                // $where['where']['order.shop_id'] = $shop_id;
                $where['whereor'] = [
                    'where' => ['orders.shop_id' => $shop_id],
                    'whereor' => [['orders.shop_str', 'like', '%.' . $shop_id . '.%']]
                ];
            }
            if (!empty($request['shop_id'])) {
                // $where['like']['orders.shop_id_str'] = '.' . $shop_id . '.' . $request['shop_id'] . '.';
                $where['whereor'] = [
                    'where' => ['orders.shop_id' => $shop_id],
                    'whereor' => [['orders.shop_str', 'like', '%.' . $shop_id . '.%']]
                ];
            }
            if (!empty($request['express_number'])) {
                $where['where']['orders_user.express_number'] = $request['express_number'];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            if (!empty($request['contact_phone'])) {
                $where['where']['orders_user.contact_phone'] = $request['contact_phone'];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            if (!empty($request['contact_name'])) {
                $where['where']['orders_user.contact_name'] = $request['contact_name'];
            }
            if (!empty($request['number'])) {
                $where['like']['orders_user.name'] = $request['number'];
            }
            if (!empty($request['product_id'])) {
                $where['where']['orders.product_id'] = $request['product_id'];
            }
            if (!empty($request['author_id'])) {
                $where['where']['orders_user.author_id'] = $request['author_id'];
            }
            if (!empty($request['province'])) {
                $where['like']['orders_user.post_province'] = $request['province'];
            }
            if (!empty($request['city'])) {
                $where['like']['orders_user.post_city'] = $request['city'];
            }
            $timeType = 'created_at';
            if (!empty($request['time_type'])) {
                switch ($request['time_type']) {
                    case 1:
                        $timeType = 'orders_user.created_at';
                        break;
                    case 2:
                        $timeType = 'orders.three_time_at';
                        break;
                    case 3:
                        $timeType = 'orders.deliver_at';
                        break;
                    case 4:
                        $timeType = 'orders.activat_at';
                        break;
                }
            }
            if (!empty($request['is_online'])) {
                $where['where']['is_online'] = $request['is_online'];
                $where['where']['status'] = 40;
            }
            //时间验证
            if (!empty($request['dateRange'])) {
                // $time = $request->get('dateRange');
                $where['between'] = [$timeType => $request['dateRange']];
            }
        }
        $where['limit']['start'] = 0;
        $where['limit']['number'] = 100000;
        $where['join'][] = [
            'table' => 'orders_user',
            'left' => 'id',
            'right' => 'orders.orders_user_id'
        ];
        $where['select'] = ['orders.*', 'orders_user.*', 'orders_user.remark as remarks'];
        // var_dump($where);
        $resData = $model->index($where, $shop_id);
        // var_dump($resData);
        $model = new Excel();
        $title = [
            '订单编号',
            '订单编号',
            '上游编号',
            '下游编号',
            '来源',
            '分销商',
            '商品名称',
            '用户姓名',
            '用户联系电话',
            '证件信息',
            '购买手机号',
            '购买手机号的串号',
            '订单状态',
            '提交失败信息',
            '当前渠道',
            '失败信息',
            '达人id',
            '达人昵称',
            '快递名称',
            '快递单号',
            '分销商',
            '上游返回状态',
            '提交时间',
            '激活时间',
            '备注'
        ];
        $excelData = [];
        foreach ($resData['data'] as $key => $v) {
            // 处理失败的信息
            $str = '';
            if (!empty($v['channel_error_josn']) && $v['channel_error_josn'] != '[]' && is_string($v['channel_error_josn'])) {
                $arrayError = json_decode($v['channel_error_josn'], true);
                foreach ($arrayError as $keys => $val) {
                    $str .= '渠道:' . $val['channel_name'] . '失败信息' . $val['msg'];
                }
            }
            $v['pay_identity'] = str_replace(mb_substr($v['pay_identity'], 3, 11), '***', ($v['pay_identity']));
            $excelData[] = [
                $v['ordersno'],
                $v['orderno'],
                $v['sup_orderno'],
                $v['dist_orderno'],
                $v['source_type'],
                $v['shop_name'],
                $v['goods_name'],
                $v['pay_name'],
                $v['pay_phone'],
                $v['pay_identity'] . ' ',
                $v['iccid'],
                $v['imei'],
                $v['status_desc'],
                $str,
                $v['sup_name'],
                !empty($v['three_msg']) ? $v['three_msg'] : '',
                $v['author_id'],
                $v['author_name'],
                $v['express_company'],
                $v['express_number'],
                $v['sell_name'],
                $v['card_status_desc'],
                $v['created_at'],
                $v['activat_at'],
                $v['remarks']
            ];
        }
        $fielname = '/attach/excel/3/' . date('Ym') . '/' . $name . date('YmdHis') . '.xlsx';
        $model->exportFile($excelData, $title, $fielname);
        $this->model->where(['id' => $id])->update(['is_run' => 1, 'path' => $fielname]);
        return $this->returnMsg(200, '导出成功', ['fiel' => $fielname]);
    }
}
